import { defineStore } from 'pinia';
import { ElNotification } from 'element-plus';
import router from '@/router';
import { useUserStore } from '@/stores/user';

export const useWebSocketStore = defineStore('websocket', {
    state: () => ({
        socket: null,
        connected: false,
        notificationSound: new Audio('/notification.mp3')
    }),

    actions: {
        initWebSocket(token) {
            if (this.socket) {
                this.socket.close();
            }

            this.socket = new WebSocket(`ws://127.0.0.1:8080/ws/chat?token=${token}`);

            this.socket.onopen = () => {
                console.log('WebSocket连接已建立');
                this.connected = true;
            };

            this.socket.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    console.log('收到WebSocket消息:', message);

                    // 获取当前路由信息
                    const currentRoute = router.currentRoute.value;
                    const currentNegotiationId = currentRoute.params.id;

                    // 如果在聊天页面且是当前会话的消息，不显示通知
                    if (currentRoute.name === 'Chat' &&
                        message.negotiationId === parseInt(currentNegotiationId)) {
                        return;
                    }

                    // 播放提示音
                    this.notificationSound.play().catch(e => console.log('无法播放提示音:', e));

                    // 显示通知
                    ElNotification({
                        title: '新消息提醒',
                        message: message.messageType === 'TEXT' ?
                            message.content :
                            this.getMessageTypeText(message.messageType),
                        type: 'info',
                        position: 'top-right',
                        duration: 5000,
                        onClick: () => {
                           
                            const userStore = useUserStore();
                            
                            const user = userStore.getUser().roleType;
                            console.log('user', user);
                            if (user ===  3) {
                                router.push(`/device-owner/chat/${message.negotiationId}`);
                            } else if (user === 2) {
                                router.push( `/advertiser/chat/${message.negotiationId}`);
                            } else {
                                console.error('未知的用户角色:', userRole);
                                return '';
                            }
                        }
                    });
                } catch (error) {
                    console.error('WebSocket消息处理失败', error);
                }
            };

            this.socket.onerror = (error) => {
                console.error('WebSocket连接错误', error);
                this.connected = false;
            };

            this.socket.onclose = () => {
                console.log('WebSocket连接已关闭');
                this.connected = false;
            };
        },

        getMessageTypeText(messageType) {
            const typeMap = {
                'TEXT': '文本消息',
                'IMAGE': '[图片]',
                'FILE': '[文件]',
                'NEGOTIATE': '[协商提案]'
            };
            return typeMap[messageType] || messageType;
        },

        closeWebSocket() {
            if (this.socket && this.socket.readyState === WebSocket.OPEN) {
                this.socket.close();
            }
        }
    }
});